package com.google.code.irouter.portal.server;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.Validate;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Link;
import com.google.appengine.repackaged.com.google.common.base.StringUtil;
import com.google.code.irouter.batch.api.Detector;
import com.google.code.irouter.model.Api;
import com.google.code.irouter.model.Guide;
import com.google.code.irouter.model.Model;
import com.google.code.irouter.portal.client.rpc.guide.GuideResult;
import com.google.code.irouter.portal.client.rpc.guide.GuideService;
import com.google.code.irouter.utils.ApiUtil;
import com.google.code.irouter.utils.DateTimeUtil;
import com.google.code.irouter.utils.ModelUtil;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GuideServiceImpl extends RemoteServiceServlet implements GuideService {

	private static final long serialVersionUID = -1041312766359407592L;
	
	public static String getDetectorName(String id) {
		Api api = ApiUtil.get(Detector.class.getSimpleName(), id);
		return api.getName();
	}

	@Override
	public List<GuideResult> load(String tags) throws IllegalArgumentException {
		List<GuideResult> guideResultList = null;
		try {
			List<Model> objectList = new ArrayList<Model>();
			Map<String, Object> cond = new HashMap<String, Object>();
			try{
				Validate.notEmpty(tags);
				String[] tagArray = StringUtil.trimEnd(tags).split(" ");			
				List<String> tagList = Arrays.asList(tagArray);			
				cond.put("tags", tagList);
			} catch (IllegalArgumentException e) {
			}
			cond.put("owner", getThreadLocalRequest().getUserPrincipal().getName());
			objectList = ModelUtil.select(Guide.class, cond);
			guideResultList = new ArrayList<GuideResult>();
			for(Object object : objectList){
				Guide guide = (Guide) object;
				GuideResult guideResult = new GuideResult();
				guideResult.setId(guide.getKey().getId());
				guideResult.setOwner(guide.getOwner());
				guideResult.setName(guide.getName());
				guideResult.setDetector(getDetectorName(guide.getDetector()));
				guideResult.setResource(guide.getResource().getValue());
				guideResult.setFixedLink(guide.getFixedLink().getValue());
				guideResult.setCreateDate(DateTimeUtil.formatDate(guide.getCreateDate()));
				guideResult.setUpdateDate(DateTimeUtil.formatDate(guide.getUpdateDate()));
				guideResultList.add(guideResult);
			}
		} catch (Exception exception) {
			// TODO
		}
		return guideResultList;
	}

	@Override
	public boolean save(String id, String name, String detector,
			String resource, String fixedLink, String tags)
			throws IllegalArgumentException {
		boolean result = true;
		try {
			Guide guide = new Guide();
			if(id.length() > 0) {
				Key oldKey = KeyFactory.createKey(Guide.class.getSimpleName(), Long.valueOf(id));
				guide = (Guide) ModelUtil.select(Guide.class, oldKey).get(0);
			}
			List<String> tagList = new ArrayList<String>();
			try{
				Validate.notEmpty(tags);
				String[] tagArray = StringUtil.trimEnd(tags).split(" ");				
				tagList = new ArrayList<String>(Arrays.asList(tagArray));
			} catch (IllegalArgumentException e) {
			}
			guide.setOwner(getThreadLocalRequest().getUserPrincipal().getName());
			guide.setName(name);
			guide.setDetector(detector);
			guide.setResource(new Link(resource));
			guide.setFixedLink(new Link(fixedLink));		
			guide.setTags(tagList);
			if(id.length() > 0)
				guide.pushUpdateDate();
			else
				guide.pushCreatDate();
			ModelUtil.save(guide);
		} catch (Exception exception) {
			// TODO
			result = false;
		}
		return result;
	}

	@Override
	public GuideResult get(String id) throws IllegalArgumentException {
		List<Model> modelList = ModelUtil.select(Guide.class, KeyFactory.createKey(Guide.class.getSimpleName(), Long.valueOf(id)));
		GuideResult guideResult = null;
		try {
			if(modelList.size() > 0) {
				guideResult = new GuideResult();
				Guide guide = (Guide) modelList.get(0);
				guideResult.setId(Long.valueOf(id));
				guideResult.setName(guide.getName());
				guideResult.setOwner(guide.getOwner());
				guideResult.setResource(guide.getResource().getValue());
				guideResult.setFixedLink(guide.getFixedLink().getValue());
				if(guide.getTags() != null) {
					StringBuffer stringBuffer = new StringBuffer();
					for(String tag : guide.getTags()) {
						stringBuffer.append(tag);
						stringBuffer.append(" ");
					}
					guideResult.setTags(StringUtil.trimEnd(stringBuffer.toString()));
				}
				guideResult.setDetector(guide.getDetector());
			}
		} catch (Exception exception) {
			// TODO
		}
		return guideResult;
	}

	@Override
	public boolean remove(String[] ids) throws IllegalArgumentException {
		boolean result = true;
		try {
			List<Key> idList = new ArrayList<Key>();
			for(String id : ids) {
				idList.add(KeyFactory.createKey(Guide.class.getSimpleName(), Long.valueOf(id)));
			}
			ModelUtil.remove(idList);
		} catch (Exception exception) {
			// TODO
			result = false;
		}
		return result;
	}
}
